#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# Usage:
# alias hash_folder='python3 <(curl -fsSL https://gitee.com/codesprite/gist/raw/master/hash_folder_data.py)'
# hash_folder <folder>


import os
import sys
import hashlib


# 获取文件 MD5
def get_md5(path, buf_size=8192):
    md5_util = hashlib.md5()
    f = open(path, 'rb')
    while True:
        data = f.read(buf_size)
        if not data:
            break
        md5_util.update(data)
    f.close()
    return md5_util.hexdigest()


# 获取字符串 MD5
def get_string_md5(text):
    md5_util = hashlib.md5()
    md5_util.update(text.encode('utf-8'))
    return md5_util.hexdigest()


def get_all_md5(folder):
    sum = ''
    total_size = 0
    files = os.listdir(folder)
    files.sort()

    for f in files:
        path = os.path.join(folder, f)
        if os.path.isdir(path):
            md5, size = get_all_md5(path)
        if os.path.islink(path):
            pass
        else:
            md5 = get_md5(path)
            size = os.path.getsize(path)
            sw.write('%s|%s|%s|%d\n' % ('F', path, md5, size))
        sum += md5
        total_size += size

    md5 = get_string_md5(sum)
    sw.write('%s|%s|%s|%s\n' % ('D', folder, md5, total_size))
    return md5, total_size


if __name__ == '__main__':
    folder = sys.argv[1]
    print('getting hash data for ' + folder)
    sw = open(folder + '.hash_data', 'w')
    md5, size = get_all_md5(folder)
    print(md5)
    sw.close()
